package dfl.bysj.controller;


import cn.hutool.core.lang.Dict;
import com.alibaba.excel.EasyExcel;
import dfl.bysj.config.ExcelDictDTOListener;
import dfl.bysj.entity.VO.ExcelDictDTO_Student;
import dfl.bysj.exception.UnifiedException;
import dfl.bysj.result.R;
import dfl.bysj.result.ResponseEnum;
import dfl.bysj.service.StudentService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Marker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author DFL
 * @since 2022-05-17
 */
@Slf4j
@CrossOrigin
@RequestMapping("/student")
@RestController
public class StudentController {



    private StudentService studentService;

    @Autowired
    public void setStudentService(StudentService studentService) {
        this.studentService = studentService;
    }

    @ApiOperation("Excel批量导入数据字典")
    @PostMapping("/import")
    public R batchImport(
            @ApiParam(value = "Excel文件", required = true)
            @RequestParam("file") MultipartFile file) {

        try {
            InputStream inputStream = file.getInputStream();
            log.info(inputStream.toString());
            studentService.importData(inputStream);
            return R.ok().message("批量导入成功");
        } catch (Exception e) {
            //UPLOAD_ERROR(-103, "文件上传错误"),
            log.error( e.getMessage());
            throw new UnifiedException(ResponseEnum.UPLOAD_ERROR, e);

        }
    }

    @ApiOperation("Excel数据的导出")
    @GetMapping("/export")
    public void export(HttpServletResponse response) {

        try {
            // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("studentDict", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), ExcelDictDTO_Student.class).sheet("数据字典").doWrite(studentService.listDictData());

        } catch (IOException e) {
            //EXPORT_DATA_ERROR(104, "数据导出失败"),
            throw new UnifiedException(ResponseEnum.EXPORT_DATA_ERROR, e);
        }
    }

    @GetMapping("/list")
    public R list_ExcelDictDTO_Student() {
        List<ExcelDictDTO_Student> dictList = studentService.listDictData();
        return R.ok().data("list", dictList);
    }
}

